package com.shujia.day19;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
    线程池：ThreadPool

    Executors:
        static ExecutorService newCachedThreadPool() 创建一个根据需要创建新线程的线程池，但在可用时将重新使用以前构造的线程。
        static ExecutorService newFixedThreadPool(int nThreads) 创建一个线程池，该线程池重用固定数量的从共享无界队列中运行的线程。
        static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 创建一个线程池，可以调度命令在给定的延迟之后运行，或定期执行。
 */
class MyRunnable implements Runnable {

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            System.out.println(Thread.currentThread().getName() + " - " + i);
        }
    }
}

class MyCallable implements Callable{

    @Override
    public Object call() throws Exception {
        for (int i = 1; i <= 100; i++) {
            System.out.println(Thread.currentThread().getName() + " - " + i);
        }
        return null;
    }
}

public class ThreadPoolDemo1 {
    public static void main(String[] args) {
        //创建一个固定大小的线程池
        ExecutorService pool = Executors.newFixedThreadPool(2);

        //Future<?> submit(Runnable task);
//        pool.submit(new MyRunnable());
//        pool.submit(new MyRunnable());
//        pool.submit(new MyRunnable());


        // <T> Future<T> submit(Callable<T> task);
//        pool.submit(new MyCallable());
//        pool.submit(new MyCallable());
        pool.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                for (int i = 1; i <= 100; i++) {
                    System.out.println(Thread.currentThread().getName() + " - " + i);
                }
                return null;
            }
        });

//        pool.submit(new Callable<Object>() {
//            @Override
//            public Object call() throws Exception {
//                //....
//                return null;
//            }
//        });

        //关闭线程池
        pool.shutdown();
    }
}
